import React, {Component} from "react";
import { connect } from 'dva';
import { Form, Input, Button, message, Spin } from 'antd';
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { myFormatMessage, formatMsgByCn,} from "@/utils/localeUtils"
import { setStorage, getStorage, removeStorage,  } from "@/utils/utils"
import { isFunction } from "lodash-es"
import {default as api} from "@/apiConfig"
import styles from "./Login.less"
import { failHandler, jsonPost } from '@/utils/request';
import router from 'umi/router';

@connect(({login})=>({
  login,
}))
class LoginPage extends Component {
  loginFormRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      logining:false,
    }
  }

  onFinish = (values)=>{
    console.log("values:",values);
    this.loginFunc(values)
  }

  /**
   * 登录请求
   * @param ajaxData
   */
  loginFunc(ajaxData){
    this.setState({ logining: true},()=>{
      jsonPost(api.login,ajaxData).then(this._afterLogin.bind(this))
    });
  }
  _afterLogin(rsp){
    const { dispatch } = this.props;
    if(rsp && rsp.status === 200){
      let stateData = rsp.data;
      const data = {
        id: stateData.uid,
        name: stateData.user_name,
        phone: stateData.phone,
        code: stateData.userCode,
        email: stateData.email,
      };
      setStorage('userInfo', data);
      setStorage('accountInfo', stateData);

      dispatch({
        type: 'global/afterLogin'
      });
      message.success(formatMsgByCn('登录成功'), 1).then(()=>{
        let timeoutRoute = getStorage('TIMEOUT_ROUTE'); // 登录过期前访问的页面路由
        removeStorage('TIMEOUT_ROUTE');
        removeStorage('SHOWING_TIMEOUT'); // 这是用来避免重复弹出[登录过期提示框]的，登录成功后也要清空

        // 标识是不是在 “iframe" 里面
        let isIframe = "LOGIN" === getStorage('IFRAME_APP');
        // 如果是在 iframe 里，则清空标识，然后关闭当前iframe
        if(isIframe){
          removeStorage("IFRAME_APP");
          // 通过调用父窗口的 dvaDispatch 方法，触发父窗口相应的 action，以关闭 iframe
          if (window.parent && isFunction(window.parent.dvaDispatch)) {
            window.parent.dvaDispatch({
              type: 'global/loginTimeout',
              payload: false,
            });
          }
        }else{
          router.replace(timeoutRoute || "/")
        }
      })
    }else{
      if(rsp && "undefined" != typeof rsp.status){
        message.error(rsp.msg || formatMsgByCn('账号或密码错误'));
      }
    }
    this.setState({ logining: false });
  }
  render(){
    let { logining } = this.state;
    return (
      <Spin spinning={logining}>
        <div className={styles.main}>
          <h3 className={styles.title}>
            {formatMsgByCn("账号密码登录")}
          </h3>
          <Form
            ref={this.loginFormRef}
            // name="control-ref"
            layout={'horizontal'}
            onFinish={this.onFinish}
          >
            <Form.Item
              name={"uname"}
              rules={[
                {required:true,message:myFormatMessage('comp.form.input.required',{name: formatMsgByCn('账户')})}
              ]}
            >
              <Input placeholder={myFormatMessage('comp.form.input.required',{name: formatMsgByCn('账户')})}
                     prefix={<UserOutlined />}/>
            </Form.Item>
            <Form.Item
              name={"upwd"}
              rules={[
                {required:true,message:myFormatMessage('comp.form.input.required',{name: formatMsgByCn('密码')})}
              ]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder={myFormatMessage('comp.form.input.required',{name: formatMsgByCn('密码')})}/>
            </Form.Item>
            <Form.Item>
              <Button type="primary"
                      size="large"
                      loading={this.state.logining}
                      block
                      htmlType="submit">
                {formatMsgByCn("立即登录")}
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Spin>

    )
  }
}
export default  LoginPage
